package com.android.advertising;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;

public class GcmManager {
	private static final String TAG = "GcmManager";

	private static GcmManager instance = null;
	private ArticleDatabase database;
	private Context mContext;

	public static GcmManager getInstance(Context ctx) {
		if (instance == null)
			instance = new GcmManager(ctx);
		return instance;
	}

	private GcmManager(Context ctx) {
		this.mContext = ctx;
		database = ArticleDatabase.getInstance(mContext);
	}

	public void processMessage(Bundle bundle) {
		int serverId = Integer.valueOf(bundle
				.getString(Constants.ARTICLES_SERVER_ID));
		String title = bundle.getString(Constants.ARTICLES_TITLE);
		long time = Long.valueOf(bundle.getString(Constants.ARTICLES_TIME));
		String link = bundle.getString(Constants.ARTICLES_LINK);
		String thumbLink = bundle.getString(Constants.ARTICLES_THUMBLINK);
		
		Log.i(TAG, "Received message: " + title + " id  =" + serverId
				+ " time = " + time + " link = " + link + " thumbLink = "
				+ thumbLink);
		boolean existed = database.findArticleByServerId(serverId);
		if (!existed) {
			// /neu chua ton tai thi notify va insert database
			if (MainService.isReady()) {				
				Article article = new Article();
				article.setServerId(serverId);
				article.setTitle(title);
				article.setCreatedTime(time);
				article.setLink(link);
				article.setThumbLink(thumbLink);
				article.setIsRead(0);
				article.setIsactive(1);
				long recordID = database.createRecord(article);
				article.setId(recordID);
				MainService.getInstance().addNotification(
						mContext.getString(R.string.app_name), title, recordID);
			}
		}
	}

}
